<template>
  <div>
    <el-upload
      v-if="uploadType == 'headImg'"
      action=""
      :show-file-list="false"
      :on-progress="getSing"
      :before-upload="beforeUpload"
      :disabled="loading"
    >
      <el-button type="primary" :loading="loading">上传头像</el-button>
    </el-upload>
    <el-upload
      v-else-if="uploadType == 'list' || uploadType == 'videoList'"
      v-loading="loading"
      action=""
      list-type="picture-card"
      :before-upload="beforeUpload"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      :on-progress="getSing"
      :limit="limit"
      :file-list="fileList"
    >
      <i class="el-icon-plus"></i>
      <div slot="file" slot-scope="{ file }">
        <img
          v-if="uploadType == 'list'"
          class="el-upload-list__item-thumbnail"
          :src="file.url"
          alt=""
        />
        <video
          v-else
          class="el-upload-list__item-thumbnail"
          :src="file.url"
        ></video>
        <span class="el-upload-list__item-actions">
          <span
            class="el-upload-list__item-preview"
            @click="handlePictureCardPreview(file)"
          >
            <i class="el-icon-zoom-in"></i>
          </span>
          <span class="el-upload-list__item-delete" @click="handleRemove(file)">
            <i class="el-icon-delete"></i>
          </span>
        </span>
      </div>
    </el-upload>
    <el-upload
      v-else
      class="avatar-uploader"
      v-loading="loading"
      action=""
      :show-file-list="false"
      :on-progress="getSing"
      :before-upload="beforeUpload"
    >
      <img v-if="value" :src="value" class="avatar" />
      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <div class="p-video" v-if="uploadType == 'videoList'">
        <video-player
          v-if="dialogVisible"
          class="video-player vjs-custom-skin"
          ref="videoPlayer"
          :playsinline="true"
          :options="playerOptions"
        ></video-player>
      </div>
      <img v-else width="100%" :src="dialogUrl" alt="" />
    </el-dialog>
  </div>
</template>
<script>
import COS from 'cos-js-sdk-v5' //脚手架安装
import { getTempKeys, addFileLog } from '../api/home' //后台给的临时密匙
export default {
  name: 'Upload',
  props: {
    uploadType: {
      // 上传类型 // list videoList headImg avatar
      type: String,
      default: 'list'
    },
    limit: {
      // 上传数量
      type: Number,
      default: 9
    },
    fileList: {
      // 文件列表
      type: Array,
      default: function () {
        return []
      }
    },
    value: {
      // 文件值
      type: String,
      default: ''
    },
    beforeUploadFun: {
      // 上传之前限制
      type: Function,
      default() {}
    }
  },
  data() {
    return {
      loading: false,
      dialogUrl: '',
      dialogVisible: false,
      uploadFile: '',
      uploadFileName: '',
      Sign: null,

      playerOptions: {
        playbackRates: [0.5, 1.0, 1.5, 2.0, 4.0, 8.0], //可选择的播放速度
        autoplay: false, //如果true,浏览器准备好时开始回放。
        muted: false, // 默认情况下将会消除任何音频。
        loop: false, // 视频一结束就重新开始。
        preload: 'auto', // 建议浏览器在<video>加载元素后是否应该开始下载视频数据。auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）
        language: 'zh-CN',
        aspectRatio: '16:9', // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
        fluid: true, // 当true时，Video.js player将拥有流体大小。换句话说，它将按比例缩放以适应其容器。
        sources: [
          {
            type: '',
            src: '' //url地址
          }
        ],
        //poster: "../assets/img/home_top.jpg", //你的封面地址
        // width: document.documentElement.clientWidth,
        notSupportedMessage: '此视频暂无法播放，请稍后再试', //允许覆盖Video.js无法播放媒体源时显示的默认信息。
        controlBar: {
          timeDivider: true, //当前时间和持续时间的分隔符
          durationDisplay: true, //显示持续时间
          remainingTimeDisplay: false, //是否显示剩余时间功能
          fullscreenToggle: true //全屏按钮
        }
      }
    }
  },
  computed: {
    _fileList: {
      get() {
        return this.fileList
      },
      set(v) {
        this.$emit('update:fileList', v)
      }
    },
    _value: {
      get() {
        return this.value
      },
      set(v) {
        this.$emit('update:value', v)
      }
    }
  },
  methods: {
    // 上传之前钩子
    beforeUpload(file) {
      // console.log(file);
      this.loading = true
      this.uploadFile = file
      this.uploadFileName =
        Math.random().toString(36).substr(2) + new Date().getTime() + file.name
      if (!this.beforeUploadFun(file)) {
        this.loading = false
        return false
      }
    },
    // 删除图片
    handleRemove(file) {
      const fileList = this._fileList //上传列表
      for (let i in fileList) {
        if (file.uid === fileList[i].uid) {
          fileList.splice(i, 1)
        }
      }
      this._fileList = fileList
    },
    handlePictureCardPreview(file) {
      this.dialogVisible = true
      if (this.uploadType == 'videoList') {
        this.playerOptions.sources[0].src = file.url
      } else {
        this.dialogUrl = file.url
      }
    },
    getSing() {
      getTempKeys({}).then((res) => {
        this.Sign = res.data
        this.upLoad()
      })
    },
    async upLoad() {
      var that = this
      var cos = new COS({
        getAuthorization: function (options, callback) {
          callback({
            TmpSecretId: that.Sign.credentials.tmpSecretId,
            TmpSecretKey: that.Sign.credentials.tmpSecretKey,
            XCosSecurityToken: that.Sign.credentials.sessionToken,
            StartTime: that.Sign.startTime,
            ExpiredTime: that.Sign.expiredTime,
            expiration: that.Sign.expiration,
            requestId: that.Sign.requestId
          })
        }
      })
      cos.putObject(
        {
          Bucket: 'inventor-1304541390',
          Region: 'ap-shanghai',
          Key: that.uploadFileName,
          StorageClass: 'STANDARD',
          Body: that.uploadFile, // 上传文件对象
          onProgress: function (progressData) {}
        },
        function (err, data) {
          that.loading = false
          if (data && data.statusCode === 200) {
            addFileLog({ key: that.uploadFileName }).then(() => {
              const url = that.imgserver + that.uploadFileName //根据对应路径获取到url
              if (that.uploadType == 'list' || that.uploadType == 'videoList') {
                that._fileList.push({ url })
              } else {
                that._value = url
              }
            })
          }
        }
      )
    }
  }
}
</script>
<style lang="scss" scoped>
/deep/ {
  .el-button {
    padding: 16px 35px;
    font-size: 20px;
  }

  .avatar-uploader .el-upload {
    width: 148px;
    height: 148px;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar {
    width: 148px;
    height: 148px;
    display: block;
  }
}
</style>